package enduringLink;

import enduringLink.call.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import producer.PartAndLineItemHandler;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.Properties;

public class RemoteServer {

    private static int instanceId;
    private static int port;
    private static String hostname;
    public static void startEnduringListen(int id){
        instanceId = id;
        Properties properties = new Properties();
        try {
            InputStream is = PartAndLineItemHandler.class.getClassLoader().getResourceAsStream("address.properties");
            properties.load(is);
            port = Integer.parseInt(properties.getProperty("port_enduring" + instanceId));
            hostname = properties.getProperty("hostname" + instanceId);
        } catch (IOException e) {
            e.printStackTrace();
        }

        MyStartLoad myStartLoad = new MyStartLoad(instanceId);
        MyStartSelect myStartSelect = new MyStartSelect();
        MyQuantityHandle myQuantityHandle = new MyQuantityHandle();
        MyTransfer myTransfer = new MyTransfer(myQuantityHandle);

        Dispatcher dis = Dispatcher.getDis();

        dis.register(StartLoad.class.getName(), myStartLoad);
        dis.register(StartSelect.class.getName(), myStartSelect);
        dis.register(QuantityHandle.class.getName(), myQuantityHandle);
        dis.register(Transfer.class.getName(), myTransfer);

        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup worker =  boss;

        ServerBootstrap sbs = new ServerBootstrap();
        ChannelFuture bind = sbs.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new RequestDecode());
                        p.addLast(new RequestHandler(dis));
                    }
                }).bind(new InetSocketAddress(hostname, port));


        try {
            bind.sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
